package a01_Array;

/**
 * @Author quan
 * @Description 数组中的二分查找
 * 普通方法：给数组和目标值，返回目标值所在的索引（必须是有序数组）
 * 还可以使用递归的二分法查找(见课件，自己还没实现)
 * @Date 2023/2/28 20:05
 */
public class BinSearch {
    public static void main(String[] args) {
        int[] arr = {1,3,5,6,7,8,9,10,12};
        int index = binSearchFun(arr,8);
        System.out.println(index);
    }
    public static int binSearchFun(int[] arr,int targetNum){
        int midIndex;
        int leftIndex = 0;
        int rightIndex = arr.length-1;
        while (leftIndex<rightIndex){
            midIndex = (leftIndex+rightIndex)/2;
            if(arr[midIndex] == targetNum){
                return midIndex;
            } else if (targetNum > arr[midIndex]) {
                leftIndex = midIndex+1;
            } else if (targetNum < arr[midIndex]) {
                rightIndex = midIndex-1;
            }
        }
        return -1;
    }
}
